import ujson,time,machine
import ubinascii

version = '2024.12.26.01' #版本号

error_code = 0       #错误代码   
error_str = "null"   #错误描述
run_status = "null"  #运行状态

devic_id  = "None"
wifi_name = "None"
wifi_psw  = "None"

#mqtt 环信服务器
mqtt_name   = 'mqtt_name'       #用户名
mqtt_passwd = "mqtt_passwd"     #mqtt密码
client_id   = "client_id"       #实例id
mserver     = 'mserver'         #服务器地址
port        =  1883             #端口

#唯一ID
unique_id   = "null"

type_net = 0  #0:WIFI 1:4G

ota_url = "https://light.gzxszn.com/ota/bin"

#读取参数
def read_config():
    global devic_id,wifi_name,wifi_psw,client_id,ota_url
    global mqtt_name,mqtt_passwd,mserver,port,type_net,unique_id,client_id2
    
    unique_id   = ubinascii.hexlify(machine.unique_id()).decode() #唯一ID

    try:
        #获取设备id
        with open('/config.json','r') as f:
            config = ujson.loads(f.read())

            #设备ID
            devic_id  = config['devic_id']
            devic_id  = unique_id
            print(devic_id)

            #获取wifi
            wifi_name  = config['wifi_name']
            wifi_psw   = config['wifi_psw']

            #mqtt
            client_id  = config['client_id']     
            mqtt_name  = config['mqtt_name']
            mqtt_passwd  = config['mqtt_passwd']
            mserver  = config['mserver']
            port  = config['port']
            
            #网络类型
            type_net = config['type_net']

            #ota 地址
            if ota_url in config:
                ota_url  = config['ota_url']
            
    except Exception as e:
        print(e)
        print('读取配置文件错误!')

def save_config():
    with open('/config.json','w') as f:
        config_file = {
                        "devic_id":devic_id,
                        "wifi_name":wifi_name,
                        "wifi_psw":wifi_psw,
                        "client_id":client_id,
                        "mqtt_name":mqtt_name,
                        "mqtt_passwd":mqtt_passwd,
                        "mserver":mserver,
                        "port":port,
                        "type_net":type_net
                        }
        str_json = ujson.dumps(config_file)  #转json字符
        f.write(str_json)
        f.flush()
        f.close()
        
def save_wifi_config():
    try:
        config_file = {"wifiname": wifi_name,"wifipassword":wifi_psw}
        f=open("/wificonfig.json","w")
        str_json = ujson.dumps(config_file)  #转json字符
        f.write(str_json)
        f.flush()
        f.close()
        print(str_json)
        
    except Exception:
        print('保存配置wifi文件错误!')

def save_device_id(id):
        with open('/config.json','w') as f:
            config_file = {"devic_id":id}
            str_json = ujson.dumps(config_file)  #转json字符
            f.write(str_json)
            f.flush()
            f.close()


